package org.client.iot.ui.ble;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.ACCESS_WIFI_STATE;
import static android.Manifest.permission.CHANGE_WIFI_STATE;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pInfo;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.material.textfield.TextInputEditText;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import org.client.iot.R;
import org.client.iot.ble.BleTemplate;
import org.client.iot.ble.WifiScanner;
import org.client.iot.databinding.ActivityBindBleBinding;
import org.client.iot.domain.WifiInfo;
import org.client.iot.ui.ble.adapter.ScanResultAdapter;
import org.client.iot.util.PermissionManager;
import org.tzw.template.base.BaseActivity;
import org.tzw.template.logger.LocalLogger;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import cn.hutool.core.util.StrUtil;

public class BindBleActivity extends BaseActivity<ActivityBindBleBinding> {

    private ScanResultAdapter scanResultAdapter;
    private int projectId;
    private WifiScanner wifiScanner;
    private MaterialDialog wifiPwdDialog;

//    private ActivityResultLauncher<Intent> startBLE = registerForActivityResult(
//            new ActivityResultContracts.StartActivityForResult(),
//            new ActivityResultCallback<ActivityResult>() {
//                @Override
//                public void onActivityResult(ActivityResult result) {
//                    if (result.getResultCode() == Activity.RESULT_OK) {
//                        Log.d(getTagName(), "onActivityResult: RESULT_OK");
//                        wifiScan();
//                    }
//                }
//            });

    @Override
    protected void initData() {
        scanResultAdapter = new ScanResultAdapter(new ArrayList<>());
        projectId = getIntent().getIntExtra("projectId", 0);
        wifiScanner = new WifiScanner(this);
    }

    @Override
    protected void initView() {
        setSupportActionBar(mRoot.toolbarBindBle);
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//添加默认的返回图标
//        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用

        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRoot.recyScanList.setLayoutManager(manager);

        mRoot.recyScanList.setAdapter(scanResultAdapter);
        mRoot.recyScanList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
    }

//    private BleDevice targetDevice;

    @Override
    protected void initListener() {
//        BleTemplate.getInstance().addDataChangeListener(this.getTagName(), dataChangeListener);
        mRoot.btnScan.setOnClickListener((v) -> {
            wifiScan();
        });
        mRoot.imgBack.setOnClickListener(v -> {
            finish();
        });
//            BleDevice bleDevice = scanResultAdapter.getData().get(position);
//            BleTemplate.getInstance().stopSearch();
//            if(BleTemplate.getInstance().isConnected()){
//                BleTemplate.getInstance().cancelConnect();
//            }
//            targetDevice = bleDevice;
//            BleTemplate.getInstance().start(bleDevice);
        scanResultAdapter.setOnItemClickListener(bleDevice -> {
            if (wifiPwdDialog != null && wifiPwdDialog.isShowing()) return;
            wifiPwdDialog = new MaterialDialog.Builder(BindBleActivity.this).title(StrUtil.format("{}-{}",bleDevice.getSsid(),bleDevice.getFrequencyTag()))
                    .customView(R.layout.dialog_wifi_add_device_item, true)
                    .positiveText("确定")
                    .negativeText("取消")
                    .callback(new MaterialDialog.ButtonCallback() {
                        @Override
                        public void onPositive(MaterialDialog dialog) {
                            TextInputEditText projectNameEdit = dialog.findViewById(R.id.textInput_wifi_pwd);

                            String wifiPwd = Objects.requireNonNull(projectNameEdit.getText()).toString();

                            if (wifiPwd.isEmpty()) {
                                showToastShort(getString(R.string.common_no_wifi_pwd));
                                return;
                            }
                            bleDevice.setPwd(wifiPwd);
                            Intent intent = new Intent();
                            intent.putExtra("targetDev", bleDevice);
                            intent.putExtra("projectId", projectId);
                            redirectToActivityWithParameters(BleConnectActivity.class, intent);
                            finish();
                        }
                    }).show();
        });
    }

    private void wifiScan() {
        PermissionManager.checkPermission(this, new PermissionManager.AcceptPermissionListener() {
            @Override
            public void onSuccess() {
//                if (!wifiScanner.()) {
//                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//                    startBLE.launch(enableBtIntent);
//                }else{
//                    startWifiScan();
//                }
                startWifiScan();
            }

            @Override
            public void onFail() {
                showToastShort(getString(R.string.bind_ble_permission_error));
            }

            @Override
            public void onError(Throwable e) {
                showToastShort("error:" + e.getCause());
                LocalLogger.e(getTagName(), "蓝牙权限获取异常:" + e.getCause());
            }
        }, ACCESS_FINE_LOCATION, CHANGE_WIFI_STATE, ACCESS_WIFI_STATE, ACCESS_COARSE_LOCATION);
    }

    private void startWifiScan() {
        if (BleTemplate.getInstance().isScan()) {
            showToastShort(getString(R.string.bind_ble_scaning));
            return;
        }
        scanResultAdapter.clearAll();
//        BleTemplate.getInstance().searchDevice();
//        mRoot.btnScan.setText(getString(R.string.bind_ble_btn_scaning));
//        mRoot.btnScan.setEnabled(false);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        wifiScanner.startScan(new WifiScanner.ScanCallback() {
            @Override
            public void onScanStarted() {
                mRoot.btnScan.setText(getString(R.string.bind_ble_btn_scaning));
                mRoot.btnScan.setEnabled(false);
            }

            @Override
            public void onScanResults(List<WifiP2pDevice> devices) {
                mRoot.btnScan.setText(getString(R.string.bind_ble_btn_scan));
                mRoot.btnScan.setEnabled(true);
                for (WifiP2pDevice matchedResult : devices) {
//                    matchedResult.primaryDeviceType
//                    matchedResult.secondaryDeviceType
//                    scanResultAdapter.addData(new WifiInfo(matchedResult.deviceName, matchedResult.deviceAddress, matchedResult.capabilities, matchedResult.frequency, wifiScanner.getWifiBand(matchedResult), matchedResult.level,""));
//                    scanResultAdapter.addData(new WifiInfo(matchedResult.deviceName, matchedResult.deviceAddress, "", 0, "", 0,""));
                    scanResultAdapter.addData(matchedResult);
                }

            }

//            @Override
//            public void onScanResults(List<ScanResult> allResults, List<ScanResult> matchedResults) {
//                mRoot.btnScan.setText(getString(R.string.bind_ble_btn_scan));
//                mRoot.btnScan.setEnabled(true);
//                for (ScanResult matchedResult : allResults) {
//                    scanResultAdapter.addData(new WifiInfo(matchedResult.SSID, matchedResult.BSSID, matchedResult.capabilities, matchedResult.frequency, wifiScanner.getWifiBand(matchedResult), matchedResult.level,""));
//                }
//            }

            @Override
            public void onScanFailed(String reason) {
                showToastShort("扫描失败: " + reason);
                mRoot.btnScan.setText(getString(R.string.bind_ble_btn_scan));
                mRoot.btnScan.setEnabled(true);
            }

            @Override
            public void onP2pDisabled() {
                mRoot.btnScan.setText(getString(R.string.bind_ble_btn_scan));
                mRoot.btnScan.setEnabled(true);
                showToastShort("请先开启 Wi-Fi");
//                WifiScanner.goToWifiSettings(BindBleActivity.this);
            }

            @Override
            public void onConnectionInfoAvailable(WifiP2pInfo info) {

            }

//            @Override
//            public void onWifiDisabled() {
//                mRoot.btnScan.setText(getString(R.string.bind_ble_btn_scan));
//                mRoot.btnScan.setEnabled(true);
//                showToastShort("请先开启 Wi-Fi");
//                WifiScanner.goToWifiSettings(BindBleActivity.this);
//            }
        });
    }
//    private BleTemplate.DataChangeListener dataChangeListener = new BleTemplate.DataChangeListener() {
//        @Override
//        public void onDeviceFounded(BleDevice bleDevice) {
//            scanResultAdapter.addData(bleDevice);
//        }
//
//        @Override
//        public void onDeviceFoundStop(List<BleDevice> bleDeviceList) {
//            mRoot.btnScan.setText(getString(R.string.bind_ble_btn_scan));
//            mRoot.btnScan.setEnabled(true);
//        }
//    };

    @Override
    protected void onDestroy() {
        BleTemplate.getInstance().stopSearch();
        BleTemplate.getInstance().removeDataChangeListener(this.getTagName());
        super.onDestroy();
    }
}